/*
 * aks_string.c
 *
 *  Created on: 2011/06/15
 *      Author: AKS 
 */
#include "core/include/aks_processor.h"

#include "core/include/aks_string.h"
#include "core/include/types.h"

BYTE hex2Ascii( BYTE hex )
{
	hex = hex & 0x0F;
	return (hex>9) ? ('A'+hex-0x0A) : ('0'+hex-0x00);
}

BYTE *writeUHex( DWORD dat, BYTE *buf, DWORD buflen )
{
	signed int lvl = 28;

	while( 0 == (dat >> lvl) && (lvl > 0) )
	{
		lvl -= 4;
	}

	for( ; (lvl >= 0) && buflen > 1 ; lvl -= 4, (buflen--), buf++)
	{
		*buf = hex2Ascii( (BYTE)(dat >> lvl) );
	}

	/* Traditional C. Haha */
	*buf = '\0';

	return buf;
}

BYTE *writeUHex_Fill( DWORD dat, DWORD len, BYTE *buf, DWORD buflen )
{
	signed int lvl = 28;

	while( 0 == (dat >> lvl) && (lvl > 0) )
	{
		lvl -= 4;
	}

	signed int nChars = len*4 - 4;

	while(nChars > lvl)
	{
		*buf = hex2Ascii(0x00);
		buf++;
		nChars -= 4;
	}

	for( ; (lvl >= 0) && buflen > 1 ; lvl -= 4, (buflen--), buf++)
	{
		*buf = hex2Ascii( (BYTE)(dat >> lvl) );
	}

	/* Traditional C. Haha */
	*buf = '\0';

	return buf;
}

BYTE *writeUDec( DWORD dat, BYTE *buf, DWORD buflen )
{
	BYTE *retPtr;

	if( dat == 0 )
	{
		buf[0] = '0';
		buf[1] = '\0';

		retPtr = &(buf[1]);
	}
	else
	{
		unsigned long mirror = dat;
		BYTE index = 0;

		while( mirror != 0 )
		{
			mirror = mirror / 10;
			index++;
		}

		if( index > buflen )
		{
			buf[0] = 'E';
			buf[1] = '\0';

			retPtr = &(buf[1]);
		}
		else
		{
			// delimita
			buf[index] = '\0';
			retPtr = &(buf[index]);
			index--;

			for( ; index >= 0 ; index-- )
			{
				buf[index] = hex2Ascii(dat % 10);
				dat = dat / 10;
			}
		}
	}

	return retPtr;
}

BYTE *writeSDec( SDWORD dat, BYTE *buf, DWORD buflen )
{
	return 0;
}

BYTE *write_Str( const BYTE *str, BYTE *buf, DWORD buflen )
{
	for( ; *str != '\0' && buflen > 1 ; buf++, str++, buflen-- )
	{
		*buf = *str;
	}

	*buf = '\0';

	return buf;
}

BOOL aks_strncmp(BYTE *str1, BYTE *str2, BYTE len)
{
	while(len!=0 && *str1 == *str2)
	{
		str1++;
		str2++;
		len--;
	}

	if(*str1=='\0' || *str2=='\0')
	{
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

BYTE *split(BYTE *str, BYTE token)
{
	while(*str != '\0')
	{
		if(*str == token)
		{
			return (str+1);
		}

		str++;
	}

	return str;
}

BYTE strnlen(BYTE *str, BYTE max)
{
	BYTE len = 0;

	while( *str != '\0' && max )
	{
		len++;
		str++;
		max--;
	}

	return len;
}
